const fs = require('fs');
const path = require('path');
const { ip, port } = require('../config');
// 上传图片模块
var express = require('express');
const multer = require('multer');
//设置上传的路径
const upload = multer({ dest: 'public/uploads' });
var router = express.Router();
//解析对应键的数据
router.use(upload.single('file'));

// 根据请求的url来返回图片
router.get('/file/:filename', async function (req, res) {
  const { filename } = req.params;
  let filePath = path.dirname(__dirname) + '/public/img/' + filename;
  try {
    res.sendFile(filePath);
  } catch (err) {
    res.send({
      code: 444,
      message: '404notfond',
    });
  }
});

// 接收前台发来的图片并将二进制文件夹存储到public文件夹下的img文件中
router.post('/img', async function (req, res) {
  console.log(req.file);
  console.log(req.body);
  try {
    fs.readFile(req.file.path, (err, data) => {
      console.log(err);
      if (err) {
        return res.send('上传失败');
      }
      let time =
        Date.now() +
        parseInt(Math.random() * 999) +
        parseInt(Math.random() * 2222);
      let extname = req.file.mimetype.split('/')[1];
      let keepname = time + '.' + extname;
      console.log(keepname);
      let basename = path.dirname(__dirname);
      console.log(basename);
      fs.writeFile(
        path.join(basename, '/public/images/' + keepname),
        data,
        (err) => {
          if (err) {
            return res.send('写入失败');
          }
          res.send({
            err: 0,
            msg: '上传ok',
            imageUrl: `http://${ip}:${port}/images/${keepname}`,
          });
        }
      );
    });
  } catch (err) {
    res.send({
      err: 400,
      msg: '上传error',
      imageUrl: ``,
    });
  }
});

module.exports = router;
